package com.ljy.jymail.product.web;

import com.ljy.common.utils.R;
import com.ljy.jymail.product.Util.IpUtils;
import com.ljy.jymail.product.entity.CategoryEntity;
import com.ljy.jymail.product.service.CategoryService;
import com.ljy.jymail.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@Slf4j
public class IndexController {


    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;


    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/getIp/getAddr")
    @ResponseBody
    public R getIp(HttpServletRequest request){

        String ipAddr = IpUtils.getIpAddr(request);
        String address = IpUtils.getAddress(ipAddr);


        log.error("ip地址是:"+ipAddr+"所属地是"+address);
        HashMap<String,String> ipInfo = new HashMap<>();
        ipInfo.put("ipAddr",ipAddr);
        ipInfo.put("address",address);

        return R.ok().put("ipInfo",ipInfo);
    }

    @GetMapping("vue-test")
    @ResponseBody
    public String testVueSpringboot(){
        return "feign调用成功";
    }

    @GetMapping({"/", "index.html", ""})
    public String indexPage(Model model) {

        //TODO: 查出所有的一级分类
        List<CategoryEntity> categoryList = categoryService.getLevelCategorys();
        //默认前缀后缀: classpath./templates/ + 返回值 +.html
        model.addAttribute("categorys", categoryList);
        return "index";
    }


    @GetMapping("index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatelogJson() {

        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }


    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //锁名相同，就是同一把锁
        RLock myLock = redisson.getLock("my-lock");

        //加锁
        myLock.lock();//10秒自动解锁,自动解锁时间一定要大于业务的执行时间
        //锁时间到了之后，不会进行自动续期
        //如果传递了锁的超时时间，就让redis执行lua脚本，默认超时就是我们指定的时间
        //如果我们未指定锁的超时时间，就是用lockWatchLock默认时间    默认时间 30*1000 ms
        //如果未指定看门时间，只要占锁成功，就会启动一个定时任务【重新给锁设置过期时间】
        //三分之一的看门时间后，会进行续期
        try {
            System.out.println("加锁成功,执行业务......." + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e) {
            e.getMessage();
        } finally {
            myLock.unlock();
            System.out.println("解锁成功");
        }
        return "hello";
    }


    //写:改数据加写锁,写锁是一个互斥锁(排他锁)，只要写锁不释放，读锁就必须等待
    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        String uuid = "";
        //获取读写锁
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        //加写锁
        RLock rLock = lock.writeLock();
        try {
            rLock.lock();
            uuid = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue", uuid);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
        return uuid;
    }


    //读：读数据+读锁
    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        //获取读写锁，必须是同一把，根据名称决定
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String writeValue = "";
        //加读锁
        RLock rLock = lock.readLock();
        System.out.println("等待读写锁操作完成");

        try {
            rLock.lock();
            writeValue = redisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {

        } finally {
            rLock.unlock();
        }
        return writeValue;
    }


    //闭锁场景
    /*
     * 放假，锁门
     * 1班没人了，2班有人......
     * 等五个班全部走完才可以锁大门
     *
     * 操作：分布式闭锁
     * */

    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() {
        //获取闭锁
        RCountDownLatch door = redisson.getCountDownLatch("door");
        //锁开始等待闭锁完成,计数归零时解锁
        door.trySetCount(5);
        try {
            door.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "放假了....";
    }


    @GetMapping("/gogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id) {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        //计数减一
        door.countDown();
        return id + "班的人都走了...";
    }

    /*
    * 信号量场景:
    * 车库停车：
    * 3车位：
    *
    * 可以用作信号量限流
    *
    * */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");

        //获取一个信号(值)---->阻塞方法--->占一个车位，想要获取，必须先等待有空余车位
//        park.acquire();
        boolean b = park.tryAcquire();
        return "ok"+b;
    }



    @GetMapping("/go")
    @ResponseBody
    public String go(){
        RSemaphore park = redisson.getSemaphore("park");

        park.release();//释放一个车位--信号量
        return "ok";
    }


}
